import { defineConfig, loadEnv } from "vite";
import type { ConfigEnv, UserConfig } from "vite";
import vue from "@vitejs/plugin-vue";
import Components from "unplugin-vue-components/vite";
import { AntDesignVueResolver } from "unplugin-vue-components/resolvers";
import { resolve } from "path";
import { wrapperEnv } from "./src/utils/getEnv";
import { visualizer } from "rollup-plugin-visualizer";
import { createHtmlPlugin } from "vite-plugin-html";
import viteCompression from "vite-plugin-compression";
import { createSvgIconsPlugin } from "vite-plugin-svg-icons";
// @ts-ignore
import eslintPlugin from "vite-plugin-eslint";

// @see: https://vitejs.dev/config/
export default defineConfig((mode: ConfigEnv): UserConfig => {
  const env = loadEnv(mode.mode, process.cwd());
  const viteEnv = wrapperEnv(env);

  // 明确的插件数组，避免条件表达式
  const plugins = [
    vue(),
    Components({
      resolvers: [
        AntDesignVueResolver({
          importStyle: false,
          resolveIcons: true
        })
      ]
    }), //
    createHtmlPlugin({
      inject: {
        data: {
          title: viteEnv.VITE_GLOB_APP_TITLE,
        },
      },
    }),
    createSvgIconsPlugin({
      iconDirs: [resolve(process.cwd(), "src/assets/icons")],
      symbolId: "icon-[dir]-[name]",
    }),
    eslintPlugin(), 
  ];

  // 条件插件 - 更清晰的方式
  if (viteEnv.VITE_REPORT) {
    plugins.push(visualizer());
  }
  if (viteEnv.VITE_BUILD_GZIP) {
    plugins.push(
      viteCompression({
        verbose: true,
        disable: false,
        threshold: 10240,
        algorithm: "gzip",
        ext: ".gz",
      })
    );
  }

  return {
    // base: "/",
    // 别名配置
    resolve: {
      alias: {
        "@": resolve(__dirname, "./src"),
      },
    },
    // 全局CSS配置
    css: {
      preprocessorOptions: {
        less: {
          javascriptEnabled: true,
          additionalData: `@import "@/styles/var.less";`,
        },
      },
    },
    // 开发服务器配置
    server: {
      host: "0.0.0.0", //  允许外部访问
      port: viteEnv.VITE_PORT, // 从环境变量读取端口
      open: viteEnv.VITE_OPEN, //  自动打开浏览器
      cors: true, //允许跨域
      proxy: {
        "/api": {
          target: "https://mock.mengxuegu.com/mock/62abda3212c1416424630a45",
          changeOrigin: true,
          rewrite: (path) => path.replace(/^\/api/, ""),
        },
      },
    },
    // 插件配置
    plugins,
    // ESBuild配置
    esbuild: {
      pure: viteEnv.VITE_DROP_CONSOLE ? ["console.log"] : [], // ✅ 生产环境移除console
    },
    // 构建配置
    build: {
      outDir: "dist", // ✅ 输出目录
      minify: "esbuild", // ✅ 使用esbuild压缩（更快）
      rollupOptions: {
        output: {
          // 静态资源分类打包
          chunkFileNames: "assets/js/[name]-[hash].js",
          entryFileNames: "assets/js/[name]-[hash].js",
          assetFileNames: "assets/[ext]/[name]-[hash].[ext]",
        },
      },
    },
  };
});